package com.cssw.fyzb.busi.api.user;

import com.cssw.fyzb.busi.service.acct.AcctService;
import com.cssw.fyzb.busi.service.user.DistrictService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.util.*;
import com.cssw.fyzb.core.model.dodb.*;
import com.cssw.fyzb.core.model.vo.user.LoginInfoVo;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.dbframe.kit.StrKit;
import com.ydn.simplecache.SimpleCache;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.cssw.fyzb.busi.cache.CacheKeys.forVerify;
import static com.cssw.fyzb.busi.util.Bizs.ERROR_VERIFY;
import static com.cssw.fyzb.busi.util.Bizs.FROZEN_USER;

/**
 * 通过手机号和短信验证码登录
 *
 * @author Feng Chen
 */
@Function(description = "通过手机号和短信验证码登录", parameters = {
        @Parameter(name = "mobile", type = Type.String, description = "手机号码", required = true),
        @Parameter(name = "code", type = Type.String, description = "短信验证码", required = true),
        @Parameter(name = "imsi", type = Type.String, description = "设备码", required = false),
})
@Component
public class LoginByCode implements Action {


    @Autowired
    private UserService userService;

    @Autowired
    private DistrictService districtService;

    @Autowired
    private AcctService acctService;

    @Autowired
    private SimpleCache simpleCache;

    @Autowired
    private SimpleLockFactory simpleLockFactory;

    private static final Logger logger = LoggerFactory.getLogger(LoginByCode.class);

    @Override
    public Response execute(Request request) throws Exception {
        String mobile = request.getString("mobile");
        String verifyCode = request.getString("code");
        String imsi = request.getString("imsi");
        String cached = simpleCache.get(forVerify(mobile));
        try {
            // 校验验证码
            if (!verifyCode.equals(cached)) {
                return Response.fail(ERROR_VERIFY.message, ERROR_VERIFY.code);
            }

            User user = userService.getByMobile(mobile);
            if (user != null) {
                if (user.isFrozen()) {
                    return Response.fail(FROZEN_USER.message, FROZEN_USER.code);
                }
                // imsi 为空，登陆验证通过后，直接写入值
                if (StrKit.isBlank(user.getImsi())) {
                    userService.updateImsi(user.getUserId(), imsi);
                    user.setImsi(imsi);
                }
                return Response.success().put("data", convert(user));
            }
            return Response.fail(Bizs.UNKNOWN_USER.message, Bizs.UNKNOWN_USER.code);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("用户登录失败");
        }
    }

    private LoginInfoVo convert(User user) {
        LoginInfoVo vo = new LoginInfoVo();
        vo.setAvatar(user.getAvatar());
        vo.setAvatar_thumb(user.getAvatar());
        vo.setId(user.getUserId()); //用户标识
        vo.setUserId(user.getUserId()); //用户标识
        vo.setUser_nickname(user.getNickName());
        // 地区名称
        if(user.getDistrict()!=null) {
            District district = districtService.getByCode(user.getDistrict());
            if(district!=null) {
                vo.setArea(district.getDistrictName());
            }
        }
        // 城市名称
        if(user.getCity()!=null) {
            District district = districtService.getByCode(user.getCity());
            if(district!=null) {
                vo.setCity(district.getDistrictName());
            }
        }
        // 省
        if(user.getProvince()!=null) {
            District district = districtService.getByCode(user.getProvince());
            if(district!=null) {
                vo.setProvince(district.getDistrictName());
            }
        }

        vo.setAge(0);
        if (null != user.getBirthday()) {
            vo.setBirthday(TimeUtil.format(user.getBirthday(), "yyyy-MM-dd"));
        }

        vo.setCode(CodeUtil.encode(user.getUserId())); //邀请码

        Acct acct = acctService.queryAcctByUIdAndType(user.getUserId(), AcctType.ACCT_TYPE_F);
        if (null != acct){
            vo.setCoin(acct.getBalanceFee().toString());//福币
        }

        vo.setHometown(""); //不确定是什么
        vo.setIsreg("0");//注册标识，不确定怎么用
        vo.setLast_login_time("");  //最后登录时间
        vo.setLogin_type("phone");  //登录类型

        vo.setMobile(user.getMobile());  //手机号码
        vo.setSex(user.getSex());

        vo.setSignature(user.getSign());
        vo.setFaceAuth(user.getFaceAuth());

        SimpleLock simpleLock = simpleLockFactory.getLock("USER_LOGIN_" + user.getUserId());
        try {
            simpleLock.acquire();
            String token = HashUtil.md5(user.getUserId() + "" + System.currentTimeMillis());
            CmfUserToken userToken = userService.getCmfTokenByUserId(user.getUserId());

            if (null == userToken){
                userService.saveCmfToken(user.getUserId(), token);
            } else {
                userToken.setToken(token);
                //userToken.setExpireTime();
                userService.updateCmfToken(userToken);
            }

            //清除php侧的登录缓存
            simpleCache.delete("token_" + user.getUserId());

            vo.setToken(token);
        } catch (Exception e){
            logger.error("", e);
            BizUtil.exception("");
        } finally {
            try {
                simpleLock.release();
            } catch (Exception e){
                logger.error("", e);
            }
        }

        return vo;
    }

}
